#include "Face.h"

using namespace std;

/// <summary>
/// Constructor
/// </summary>
/// <param name="v"> A vector containing the face's vertices </param>
CICore::Face::Face (const CICore::VertexLib& v) : vertices(v), selected (true), visible (true) {
    //Initializing face's normal
    normal.x = 0.0f;
    normal.y = 0.0f;
    normal.z = 1.0f;
}

/// <summary>
/// Destructor
/// </summary>
CICore::Face::~Face() {
}









///<************************************************************************************************************>
///<**************************************** region Utility Methods ********************************************>
///<************************************************************************************************************>

/// <summary>
/// Method called to compute the face's normal
/// </summary>
void CICore::Face::ComputeNormal () {
//    int j;

    //normal.x = 0.0f;
    //normal.y = 0.0f;
    //normal.z = 1.0f;

    //int n = vertices.size();

    //for (int i=0; i<n; i++) {
    //    j = (i+1) % n;

    //    normal.x += (vertices[i]->z + vertices[j]->z) * (vertices[i]->y - vertices[j]->y);

    //    normal.y += (vertices[i]->x + vertices[j]->x) * (vertices[i]->z - vertices[j]->z);

    //    normal.z += (vertices[i]->y + vertices[j]->y) * (vertices[i]->x - vertices[j]->x);
    //}
    //normal.x *= 0.5;
    //normal.y *= 0.5;
    //normal.z *= 0.5;

    if (vertices.size() < 3)
        return;

    Vector3D a, b;

    a.x = vertices[0]->x - vertices[1]->x;
    a.y = vertices[0]->y - vertices[1]->y;
    a.z = vertices[0]->z - vertices[1]->z;

    b.x = vertices[1]->x - vertices[2]->x;
    b.y = vertices[1]->y - vertices[2]->y;
    b.z = vertices[1]->z - vertices[2]->z;

    normal.x = a.y*b.z - a.z*b.y;
    normal.y = a.z*b.x - a.x*b.z;
    normal.z = a.x*b.y - a.y*b.x;

    if (normal.x == 0 && normal.y == 0 && normal.z == 0)    
        normal.z = 1.0f;
    else
        normal.Normalize();
}

/// <summary>
/// Method called to set the face and its vertices as selected
/// </summary>
void CICore::Face::SetSelected () {
    selected = true;                //Sets the face as selected
    int n = vertices.size();

    for (int i = 0; i < n; i++)            //For each vertex
        vertices[i]->selected = true;               //sets the vertex as selected
        
}
/***************************************************************************************************************
******************************************* endregion Utility Methods ******************************************
****************************************************************************************************************/
